#include "blockqueue.hpp"
#include <vector>
#include <ctime>
#include <unistd.h>
using namespace std;

const int N = 5;

void* Productor(void* argc)
{
    //BlockQueue<int>* bq = static_cast<BlockQueue<int>*>(argc);
    BlockQueue<Task>* bq = static_cast<BlockQueue<Task>*>(argc);

    while(1)
    {
        //int data = rand() % 10 + 1;
        int d1 = rand() % 10 + 1;
        int d2 = rand() % 10 + 1;
        int idx = rand() % 5;
        Task t(d1, d2, OP[idx]);
        bq->push(t);
        

        //bq->push(data);
        //printf("生产者%p 生成了一个数据 %d \n", pthread_self(), data);
        usleep(10);
    }
}


void* Consumer(void* argc)
{
    //BlockQueue<int>* bq = static_cast<BlockQueue<int>*>(argc);
    BlockQueue<Task>* bq = static_cast<BlockQueue<Task>*>(argc);
    
    while(1)
    {
        //int data = bq->pop();
        //printf("消费者消费了一个数据 %d \n", data);
        Task t = bq->pop();
        t.run();
        cout << std::to_string(pthread_self()) + " " + t.getTask() + "\n";
        cout << std::to_string(pthread_self()) + " " + t.finishTask() + "\n";
        usleep(10);  
    }
}

int main()
{
    srand(time(nullptr));
    vector<pthread_t> ptids;
    vector<pthread_t> ctids;

    //BlockQueue<int>* bq = new BlockQueue<int>();
    BlockQueue<Task>* bq = new BlockQueue<Task>();

    for(int i = 1; i <= N; i++)
    {
        pthread_t tid;
        pthread_create(&tid, nullptr, Productor, bq);
        ptids.push_back(tid);
    }

    for(int i = 1; i <= N; i++)
    {
        pthread_t tid;
        pthread_create(&tid, nullptr, Consumer, bq);
        ctids.push_back(tid);
    }

    for(auto ptid : ptids)
    {
        pthread_join(ptid, nullptr);
    }

    for(auto ctid : ctids)
    {
        pthread_join(ctid, nullptr);
    }

    return 0;
}